package test2;

import java.net.URI;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor;
import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;


public class Main {

	public Object getProxy(Class<?> serviceInterface, String serviceUrl, String username, String password) throws Exception{
		URI uri = new URI(serviceUrl);
		
		CommonsHttpInvokerRequestExecutor executor = new CommonsHttpInvokerRequestExecutor();
		HttpClient client = executor.getHttpClient();
		HttpClientParams params = client.getParams();
		params.setConnectionManagerTimeout(300000); //??
		params.setSoTimeout(300000); //??
		params.setAuthenticationPreemptive(true);		//抢先认证
		client.getState().setCredentials(new AuthScope(uri.getHost(),uri.getPort()),new UsernamePasswordCredentials(username,password));
		
		HttpInvokerProxyFactoryBean factoryBean = new HttpInvokerProxyFactoryBean();
		factoryBean.setServiceInterface(serviceInterface);
		factoryBean.setServiceUrl(serviceUrl);
		factoryBean.setHttpInvokerRequestExecutor(executor);
		factoryBean.afterPropertiesSet();
		
		return factoryBean.getObject();
	}
	
	public static void main(String[] args) throws Exception{
		String serviceUrl = "http://localhost:8080/remoting/testService.rpc";
		String username = "rpc";
		String password = "123456";
		
		Main proxy = new Main();
		TestService service1 = (TestService)proxy.getProxy(TestService.class, serviceUrl, username, password);
		
		int r1 = service1.add(2, 3);
		System.out.println("r1=" + r1);

	}

}
